import {
  LineLayer,
  PointLayer,
  PolygonLayer,
  Popup,
  RasterLayer,
  Scene
} from '@antv/l7'
import { GaodeMap, Map } from '@antv/l7-maps'
import { useEffect } from 'react'

import ImageryTheme from './ImageryTheme'
const theme = new ImageryTheme({
  bgColor: 'black',
  alpha: 1,
  invert: true
})
import map from './map.json'
import outline from './outline.json'
type Fly = {
  line: LineLayer
  startPoint: PointLayer
  endPoint: PointLayer
  startText: PointLayer
  endText: PointLayer
}
const tracks = [
  [
    { lng: 111.43, lat: 34.49, name: 'A' },
    { lng: 112.45, lat: 34.62, name: 'B' }
  ],
  [
    { lng: 112.3, lat: 34.51, name: 'C' },
    { lng: 112.11, lat: 34.1, name: 'D' }
  ]
]
const detailTracks: {
  [key: string]: {
    lng: number
    lat: number
    name: string
  }[][]
} = {
  洛宁县: [
    [
      { lng: 111.26567763024582, lat: 34.22805553315325, name: '洛宁A' },
      { lng: 111.46733114978844, lat: 34.432049676288244, name: '洛宁B' }
    ],
    [
      { lng: 111.75268433982518, lat: 34.319103773762436, name: '洛宁C' },
      { lng: 111.36248477951051, lat: 34.44520513566498, name: '洛宁D' }
    ]
  ],
  嵩县: [
    [
      { lng: 112.204212492436, lat: 34.25760773262681, name: '嵩县A' },
      { lng: 112.10979888352227, lat: 33.70506776050195, name: '嵩县B' }
    ],
    [
      { lng: 111.77935125232142, lat: 34.14348038421099, name: '嵩县C' },
      { lng: 112.17879344388234, lat: 33.90421492405689, name: '嵩县D' }
    ]
  ]
}
const Home = () => {
  useEffect(() => {
    const scene = new Scene({
      id: 'map',
      map: new Map({
        pitch: 30,
        center: [112.56, 34.59],
        zoom: 6,
        token: '02ae77a271c7361f4eb5247b28f22b5b'
        // style:
        //   'https://basemaps.cartocdn.com/gl/dark-matter-nolabels-gl-style/style.json'
      })
    })

    scene.on('loaded', () => {
      let isGoDown = false
      const flys: Fly[] = []
      const polygonLayer = new PolygonLayer({
        zIndex: 2,
        autoFit: true,
        enablePropagation: true
      })
        .source(map)
        .shape('extrude')
        .style({
          heightfixed: true,
          pickLight: true,
          topsurface: true,
          raisingHeight: 0,
          opacity: 0.8
        })
        .size(30000)
        .color('name', [
          'rgba(91, 143, 249, 0.8)',
          'rgba(90, 216, 166, 0.8)',
          'rgba(93, 112, 146, 0.8)',
          'rgba(246, 189, 22, 0.8)',
          'rgba(232, 100, 82, 0.8)',
          'rgba(109, 200, 236, 0.8)',
          'rgba(148, 95, 185, 0.8)',
          'rgba(204, 26, 3, 0.8)'
        ])
        .active({ color: 'red', mix: 0.8 })

      const lineLayer2 = new LineLayer({
        zIndex: 2
      })
        .source(map)
        .shape('line')
        .size(1)
        .style({
          raisingHeight: 30000
        })
        .color('name', [
          'rgba(91, 143, 249, 0.8)',
          'rgba(90, 216, 166, 0.8)',
          'rgba(93, 112, 146, 0.8)',
          'rgba(246, 189, 22, 0.8)',
          'rgba(232, 100, 82, 0.8)',
          'rgba(109, 200, 236, 0.8)',
          'rgba(148, 95, 185, 0.8)',
          'rgba(204, 26, 3, 0.8)'
        ])
      const lineLayer = new LineLayer({
        zIndex: 2
      })
        .source(outline)
        .shape('line')
        .color('#000')
        .size(1)
        .style({
          raisingHeight: 30000
        })
      const hightLayer = new LineLayer({
        zIndex: 4, // 设置显示层级
        name: 'hightlight'
      })
        .source({
          type: 'FeatureCollection',
          features: []
        })
        .shape('line')
        .size(1)
        .color('red')
        .style({
          raisingHeight: 30000,
          opacity: 0.5
        })
      const popup = new Popup({
        offsets: [0, 14],
        closeButton: false
      })
      polygonLayer.on('mousemove', (event) => {
        // if (isGoDown) return
        hightLayer.setData({
          type: 'FeatureCollection',
          features: [event.feature]
        })
        popup
          .setLnglat(event.lngLat)
          .setHTML(`<span>${event.feature.properties.name}</span>`)
        scene.addPopup(popup)
      })
      polygonLayer.on('mouseout', () => {
        hightLayer.setData({
          type: 'FeatureCollection',
          features: []
        })
        scene.removePopup(popup)
      })
      polygonLayer.on('click', (event) => {
        if (isGoDown) return
        isGoDown = true
        lineLayer.hide()
        lineLayer2.hide()
        polygonLayer.active(false)
        polygonLayer.setData({
          type: 'FeatureCollection',
          features: [event.feature]
        })
        const name: string = event.feature.properties.name
        Fly(detailTracks[name] || [])
      })
      polygonLayer.on('unclick', () => {
        if (!isGoDown) return
        polygonLayer.active(true)
        isGoDown = false
        lineLayer.show()
        lineLayer2.show()
        polygonLayer.setData(map)
        Fly(tracks)
      })
      scene.addImage(
        '01',
        'https://gw.alipayobjects.com/zos/basement_prod/604b5e7f-309e-40db-b95b-4fac746c5153.svg'
      )
      scene.addImage(
        '02',
        'https://gw.alipayobjects.com/zos/bmw-prod/ce83fc30-701f-415b-9750-4b146f4b3dd6.svg'
      )
      const Fly = (
        tracks: {
          lng: number
          lat: number
          name: string
        }[][]
      ) => {
        tracks.forEach((track, index) => {
          const fly = {} as Fly
          const data = {
            lng: track[0].lng,
            lat: track[0].lat,
            lng1: track[1].lng,
            lat1: track[1].lat
          }
          if (!flys[index]) {
            track.forEach((point, i) => {
              const textLayer = new PointLayer({ zIndex: 10 })
              textLayer
                .source([point], {
                  parser: {
                    type: 'json',
                    x: 'lng',
                    y: 'lat'
                  }
                })
                .shape('cylinder')
                .size([8000, 8000, 200000])
                .color('#fe6c01')
                .style({
                  opacity: 0.8,
                  raisingHeight: 0,
                  opacityLinear: {
                    enable: true, // true - false
                    dir: 'down' // up - down
                  },
                  lightEnable: false,
                  heightfixed: true
                })
              const circleLayer = new PointLayer({ zIndex: 40 })
              circleLayer
                .source([point], {
                  parser: {
                    type: 'json',
                    x: 'lng',
                    y: 'lat'
                  }
                })
                .shape('01')
                .size(16)
              circleLayer.on('mousemove', (event) => {
                const name: string = event.feature.name
                popup
                  .setLnglat(event.lngLat)
                  .setHTML(`<span>变电站${name}</span>`)
              })
              if (i % 2 === 0) {
                fly.startPoint = circleLayer
                fly.startText = textLayer
              } else {
                fly.endPoint = circleLayer
                fly.endText = textLayer
              }
              scene.addLayer(textLayer)
              scene.addLayer(circleLayer)
            })
            const line = new LineLayer({ zIndex: 30, pickingBuffer: 4 })
            line
              .source([data], {
                parser: {
                  type: 'json',
                  x: 'lng',
                  y: 'lat',
                  x1: 'lng1',
                  y1: 'lat1'
                }
              })
              .shape('line')
              .size(1)
              .texture('02')
              .color('#f0f')
              .animate({
                interval: 1, // 间隔
                duration: 1, // 持续时间，延时
                trailLength: 2 // 流线长度
              })
              .style({
                lineTexture: true, // 开启线的贴图功能
                iconStep: 20 // 设置贴图纹理的间距
              })
            line.on('mousemove', (event) => {
              popup
                .setLnglat(event.lngLat)
                .setHTML(`<span>线路${index + 1}</span>`)
            })
            fly.line = line
            scene.addLayer(line)
            flys[index] = fly
          } else {
            flys[index].line.setData([data], {
              parser: {
                type: 'json',
                x: 'lng',
                y: 'lat',
                x1: 'lng1',
                y1: 'lat1'
              }
            })

            flys[index].line.show()

            track.forEach((point, i) => {
              if (i % 2 === 0) {
                flys[index].startPoint.setData([point], {
                  parser: {
                    type: 'json',
                    x: 'lng',
                    y: 'lat'
                  }
                })
                flys[index].startText.setData([point], {
                  parser: {
                    type: 'json',
                    x: 'lng',
                    y: 'lat'
                  }
                })

                flys[index].startPoint.show()
                flys[index].startText.show()
              } else {
                flys[index].endPoint.setData([point], {
                  parser: {
                    type: 'json',
                    x: 'lng',
                    y: 'lat'
                  }
                })
                flys[index].endText.setData([point], {
                  parser: {
                    type: 'json',
                    x: 'lng',
                    y: 'lat'
                  }
                })
                flys[index].endPoint.show()
                flys[index].endText.show()
              }
            })
          }
        })
        const len = tracks.length
        for (let i = len; i < flys.length; i++) {
          const fly = flys[i]
          const { line, startPoint, startText, endPoint, endText } = fly
          line.hide()
          startPoint.hide()
          startText.hide()
          endPoint.hide()
          endText.hide()
          // scene.removeLayer(line)
          // scene.removeLayer(startPoint)
          // scene.removeLayer(startText)
          // scene.removeLayer(endPoint)
          // scene.removeLayer(endText)
        }
      }
      // 飞线
      Fly(tracks)

      const layer = new RasterLayer({
        zIndex: -1
        // maskLayers: [polygonLayer]
      })
      layer.source(
        'https://tiles{1-3}.geovisearth.com/base/v1/vec/{z}/{x}/{y}?format=png&tmsIds=w&token=b2a0cfc132cd60b61391b9dd63c15711eadb9b38a9943e3f98160d5710aef788',
        // 'http://192.168.10.2/{z}/{x}/{y}.png',
        {
          parser: {
            type: 'rasterTile',
            minZoom: 3,
            maxZoom: 18,
            dataType: 'customImage',
            zoomOffset: 0,
            getCustomData: (tile, cb) => {
              console.log('tile, cb', tile, cb)
              const imageUrl = `https://tiles1.geovisearth.com/base/v1/vec/${tile.z}/${tile.x}/${tile.y}?format=png&tmsIds=w&token=b2a0cfc132cd60b61391b9dd63c15711eadb9b38a9943e3f98160d5710aef788`
              // 通过 Image 对象获取图像数据
              const img = new Image()
              img.crossOrigin = 'anonymous' // enable CORS for the image
              img.onload = () => {
                const canvas = theme.processImage(img)
                const res = new Image()
                res.src = canvas.toDataURL('image/png')
                res.onload = () => {
                  cb(null, res)
                }
              }
              img.src = imageUrl
            }
          }
        }
      )
      scene.addLayer(layer)
      scene.addLayer(hightLayer)
      // scene.addLayer(lineLayer)
      scene.addLayer(polygonLayer)
      scene.addLayer(lineLayer2)
    })
  }, [])
  return (
    <div
      style={{
        minHeight: '100%',
        justifyContent: 'center',
        position: 'relative'
      }}
      id="map"
    ></div>
  )
}
export default Home
